package com.hcloud.common.crud.aspect;

import com.hcloud.auth.api.permission.AuthorityCheckService;
import com.hcloud.auth.api.user.HcloudUserDetails;
import com.hcloud.common.core.annontion.AuthPrefix;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.crud.annon.HCloudPreAuthorize;
import com.hcloud.common.crud.controller.BaseDataController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Auther hepangui
 * @Date 2018/11/14
 */
@Aspect
@Component
@Order(20)
public class PreAuthorizeAspect {

    @Autowired
    private AuthorityCheckService authorityCheckService;

    @Around("@annotation(hCloudPreAuthorize)")
    public Object around(ProceedingJoinPoint point, HCloudPreAuthorize hCloudPreAuthorize) throws Throwable {
        Object target = point.getTarget();
        if (target instanceof BaseDataController) {
            BaseDataController baseDataController = (BaseDataController) target;
            AuthPrefix annotation = baseDataController.getClass().getAnnotation(AuthPrefix.class);
            if(annotation == null){
                return point.proceed();
            }

            String authority = new StringBuilder(annotation.value())
                    .append(hCloudPreAuthorize.value()).toString();
            if (authorityCheckService.has(authority)) {
                return point.proceed();
            } else {
                HCloudResult hCloudResult = new HCloudResult("权限不足");
                hCloudResult.setCode(HCloudResult.NOAUTH);
                return hCloudResult;
            }
        }
        return point.proceed();
    }
}
